package com.mashibing.juc.c_001;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName T06_AccountSynchronized
 * @Description 面试题  模拟银行账户
 * 对业务写方法加锁
 * 对业务读方法不加锁
 * <p>
 * 容易产生脏读问题
 * @Author xiongwei.wu
 * @Date 2021/7/1 9:50
 **/
public class T06_AccountSynchronized {
    String name;
    double balance;

    public synchronized void set(String name, double balance) {
        this.name = name;
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
    }

    /**
     * 不允许加锁就会产生脏读的场景
     *
     * @param name
     * @return
     */
    public /*synchronized*/ double getBalance(String name) {
        return balance;
    }

    public static void main(String[] args) {
        T06_AccountSynchronized account = new T06_AccountSynchronized();
        new Thread(() -> {
            account.set("zhangsan", 1000.0);
        }).start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(account.getBalance("zhangsan"));

        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(account.getBalance("zhangsan"));
    }
}
